﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using ProtoBuf;
using UnityEngine;
namespace TinySkill
{
    //技能数据存取类
    public class Data
    {

        public static Dictionary<int, config_skill> Skill;

        //获取技能
        public static config_skill GetSkill(int id)
        {
            config_skill p = null;
            if (Skill.TryGetValue(id, out p))
            {
                return p;
            }

            return null;
        }

        //加载所有技能
        public static void LoadSkill()
        {
            List<config_skill> skillList = null;
            try
            {
                //技能类型比较复杂，自行序列化，不走Unity的序列化
                MemoryStream ms = new MemoryStream(File.ReadAllBytes(Path.Combine(Application.dataPath + "/StreamingAssets/", "Skill/skill.bin")));
                ms.Position = 0;
                skillList = ProtoBuf.Serializer.Deserialize<List<config_skill>>(ms);

                if (Application.isPlaying)
                {
                    foreach (var s in skillList)
                    {
                        s.Sorts();
                    }
                }

            }
            catch (Exception e)
            {
                Debug.LogError(e.Message);
                skillList = new List<config_skill>();
            }

            Skill = new Dictionary<int, config_skill>();
            foreach (var s in skillList)
            {
                Skill.Add(s.id, s);
            }
        }

        //存储所有技能
        public static void SaveSkill()
        {
            if (Data.Skill == null)
                return;

            List<config_skill> skills = new List<config_skill>();
            foreach (var d in Data.Skill)
            {
                skills.Add(d.Value);
            }
            MemoryStream ms = new MemoryStream();
            Serializer.Serialize(ms, skills);
            byte[] data = new byte[ms.Position];
            ms.Position = 0;
            ms.Read(data, 0, data.Length);
            try
            {
                File.WriteAllBytes(Path.Combine(Application.dataPath + "/StreamingAssets/", "Skill/skill.bin"), data);
            }
            catch (Exception exc)
            {
                Debug.LogError("保存失败 " + exc.Message);
                return;
            }
            Debug.Log("技能保存成功");
        }


    }
}


